package com.nondo.dean.order.service;

import java.math.BigDecimal;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.Iterator;
import java.util.List;
import java.util.Map;
import java.util.Set;

import org.apache.commons.collections.CollectionUtils;
import org.apache.commons.collections.map.HashedMap;
import org.apache.ibatis.session.RowBounds;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import org.springframework.transaction.annotation.Propagation;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.web.client.RestTemplate;

import com.nondo.dean.auth.common.TokenPrincipalProvider;
import com.nondo.dean.common.tool.AliyunOssTool;
import com.nondo.dean.common.tool.BeanUtils;
import com.nondo.dean.common.tool.StringUtils;
import com.nondo.dean.common.web.View;
import com.nondo.dean.order.common.Constant;
import com.nondo.dean.order.common.DateProcessUtils;
import com.nondo.dean.order.common.OrderTip;
import com.nondo.dean.order.common.OrderUtils;
import com.nondo.dean.order.domain.Cart;
import com.nondo.dean.order.domain.OrderDetail;
import com.nondo.dean.order.domain.OrderLog;
import com.nondo.dean.order.domain.OrderSubject;
import com.nondo.dean.order.domain.OrderSubjectExample;
import com.nondo.dean.order.mapper.OrderSubjectExtendsMapper;
import com.nondo.dean.order.mapper.OrderSubjectMapper;
import com.nondo.dean.order.model.AuthUserBean;
import com.nondo.dean.order.model.ConsigneeBean;
import com.nondo.dean.order.model.OrderDetailBean;
import com.nondo.dean.order.model.ProductBomBean;
import com.nondo.dean.order.model.UserBean;
import com.nondo.dean.order.model.param.AppOrderParam;
import com.nondo.dean.order.model.param.AppOrderParam.CartParam;
import com.nondo.dean.order.model.param.OrderProductParam;
import com.nondo.dean.order.model.param.OrderStatusParam;
import com.nondo.dean.order.model.param.OrderSubjectSearchParam;
import com.nondo.dean.order.model.param.OrderTransmitParam;
import com.nondo.dean.order.model.param.PlatformOrderParam;
import com.nondo.dean.order.model.param.ProductOrderParam;
import com.nondo.dean.order.model.result.AppOrderResult;
import com.nondo.dean.order.model.result.OrderSubjectDetailResult;
import com.nondo.dean.order.model.result.OrderSubjectDetailResult.OrderDetailResult;
import com.nondo.dean.order.model.result.OrderSubjectResult;
import com.nondo.dean.order.model.result.OrderSubjectSearchResult;
import com.nondo.dean.order.model.result.ProductResult;

/**
 * 订单管理业务类
 *
 * @author zhaoljin
 * @date 2018年4月18日
 */
@Component
public class OrderService {

    @Autowired
    private PushService pushService;

    @Autowired
    private OrderSubjectMapper orderMapper;

    @Autowired
    private UserService userService;

    @Autowired
    private StoreService storeService;

    @Autowired
    private CartService cartService;

    @Autowired
    private ProductService produtService;

    @Autowired
    private OrderLogService orderLogService;

    @Autowired
    private OrderDetailService orderDetailService;

    @Autowired
    private OrderSubjectExtendsMapper orderSubjectExtendsMapper;

    @Autowired
    private RestTemplate restTemplate;

    @Autowired
    private AliyunOssTool aliyunOssTool;

    @Autowired
    private TokenPrincipalProvider tokenPrincipalProvider;

    /**
     * 插入订单
     * @param order
     * @return
     */
    @Transactional
    public int addOrder(OrderSubject order) {
        return orderMapper.insertSelective(order);
    }

    /**
     * 修改订单
     * 并推送消息
     * @param order
     * @return
     */
    @Transactional
    public int updateOrder(OrderSubject order) {
        if(order.getOrderStatus() != null){
            pushService.addAndPushMessage(order);
        }
        return orderMapper.updateByPrimaryKeySelective(order);
    }



    /**
     * 按照主键ID查询订单
     * @param id
     * @return
     */
    public OrderSubject selectOrder(Integer id) {
        return orderMapper.selectByPrimaryKey(id);
    }

    /**
     * 订单分页查询列表
     * @param offset
     * @param limit
     * @param order
     * @return
     */
    public List<OrderSubject> getOrderList(int offset, int limit, OrderSubject order) {
        OrderSubjectExample example = new OrderSubjectExample();
        example.setOrderByClause("update_date DESC");
        RowBounds rowBounds = new RowBounds(offset, limit);
        OrderSubjectExample.Criteria criteria = example.createCriteria();
        setCriteria(criteria, order);
        return orderMapper.selectByExampleWithRowbounds(example, rowBounds);
    }

    /**
     * 订单总数统计
     * @param order
     * @return
     */
    public Long count(OrderSubject order) {
        OrderSubjectExample example = new OrderSubjectExample();
        OrderSubjectExample.Criteria criteria = example.createCriteria();
        setCriteria(criteria, order);
        return orderMapper.countByExample(example);
    }

    /**
     * 组装查询条件
     * @param criteria
     * @param order
     */
    void setCriteria(OrderSubjectExample.Criteria criteria, OrderSubject order) {
        if (order != null) {
            if (order.getId() != null)
                criteria.andIdEqualTo(order.getId());
            if (order.getUserId() != null)
                criteria.andUserIdEqualTo(order.getUserId());
            if (order.getOrderStatus() != null && order.getOrderStatus() != 0) {
                criteria.andOrderStatusEqualTo(order.getOrderStatus());
            }
            if (StringUtils.isNoneBlank(order.getOrderCode()))
                criteria.andOrderCodeLike("%" + order.getOrderCode() + "%");
        }
        criteria.andDelFlagEqualTo(OrderSubject.DEL_FLAG_NORMAL);
    }

    /**
     * APP端生成订单
     * @param orderParam 订单参数 {@link AppOrderParam}
     * @return 订单ID
     */
    @Transactional(propagation = Propagation.REQUIRED)
    public int createAppOrder(AppOrderParam orderParam) {
        OrderSubject order = new OrderSubject();
        order.setPlatform(Constant.APP_ORDER);
        // 设置收货人信息
        setConsigneeInfo(orderParam,order);
        // 设置经销商其它采购信息
        setOtherPurchaseInfo(order,null);
        // 创建订单及明细
        createOrderSubject(orderParam,order);
        // 修改库存和销量
        updateStockSaleNum(orderParam,order);
        // 发送消息通知
        pushService.addAndPushMessage(order);
        // 增加订单日志
        addOrderLog(order,Constant.LOG_TYPE_ADD);
        return order.getId();
    }

    /**
     * 增加订单日志
     * @param order 订单
     */
    private void addOrderLog(OrderSubject order, Integer type) {
        OrderLog orderLog = new OrderLog();
        Integer userId = userService.getLoginUserId();;
        String userName = userService.getLoginUserName();
        if (order.getPlatform() == Constant.PLATFORM_ORDER) {
            AuthUserBean authUserBean = null;
            userName = order.getUserName();
            authUserBean = userService.getAuthUserByUserName(userName);
            if (authUserBean == null || authUserBean.getId() == null) {
                throw new RuntimeException();
            }
            userId = authUserBean.getId();
        }
        orderLog.setType(type);
        orderLog.setUserId(userId);
        orderLog.setUserName(userName);
        orderLog.setOrderId(order.getId());
        orderLog.setOrderCode(order.getOrderCode());
        if (type == Constant.LOG_TYPE_ADD) {
            orderLog.setDescription(OrderTip.ORDER_CREATE_SUCCESS);
        } else if (type == Constant.LOG_TYPE_DEL) {
            orderLog.setDescription(OrderTip.ORDER_DELETE_SUCCESS);
        } else if (type == Constant.LOG_TYPE_UPDATE) {
            orderLog.setDescription(OrderTip.ORDER_UPDATE_SUCCESS);
        }
        orderLogService.addOrderLog(orderLog);
    }

    /**
     * 修改库存和销量
     * @param orderParam 订单参数
     * @param order 订单
     */
    private void updateStockSaleNum(AppOrderParam orderParam, OrderSubject order) {
        List<CartParam> cartParamList = orderParam.getCartList();
        for (CartParam cartParam : cartParamList) {
            ProductOrderParam productParam = new ProductOrderParam();
            productParam.setProductId(cartParam.getProductId());
            productParam.setPurchaseNum(cartParam.getNum());
            int update = produtService.updateStockSaleNum(productParam);
            if (update == 0) {
                throw new RuntimeException(OrderTip.UPDATE_STOCK_FAIL);
            }
        }
    }

    /**
     * 向订单中添加产品明细
     * @param orderParam 订单参数
     * @param order 订单
     */
    private void addOrderDetail(List<ProductResult> productList, OrderSubject order) {
        for (ProductResult productResult : productList) {
            OrderDetail orderDetail = new OrderDetail();
            orderDetail.setOrderCode(order.getOrderCode());
            orderDetail.setOrderId(order.getId());
            // 设置产品信息
            setOrderDetail(productResult, orderDetail);
            orderDetailService.addOrderDetail(orderDetail);
            // 设置产品BOM信息
            Integer orderId = orderDetail.getId();
            Integer purchaseNum = productResult.getPurchaseNum();
            String productCode = orderDetail.getProductCode();
            List<ProductBomBean> productBomList = produtService.getProductBomListByParentCode(productCode);
            // 保存主件的子件信息存储结构同主件
            for (ProductBomBean productBom : productBomList) {
                productCode = productBom.getProductCode();
                productResult = produtService.getProductBeanByCode(productCode);
                productResult.setPurchaseNum(purchaseNum);
                setOrderDetail(productResult, orderDetail);
                orderDetail.setUpId(orderId);
                orderDetail.setBomQuantity(productBom.getBomUnit());
                orderDetailService.addOrderDetail(orderDetail);
            }
        }
    }

    /**
     * 设置订单明细信息
     * @param productResult 产品详情
     * @param orderDetail 订单明细详情
     * @return
     */
    private void setOrderDetail(ProductResult productResult, OrderDetail orderDetail) {
        orderDetail.setProductId(productResult.getId());
        orderDetail.setProductCode(productResult.getCode());
        orderDetail.setProductName(productResult.getName());
        orderDetail.setProductImage(productResult.getMainImage());
        orderDetail.setProductPrice(productResult.getSalePrice());
        orderDetail.setPurchaseQuantity(productResult.getPurchaseNum());
        BigDecimal purchaseNum = new BigDecimal(productResult.getPurchaseNum());
        orderDetail.setAmount(productResult.getSalePrice().multiply(purchaseNum));
        orderDetail.setProductImage(productResult.getMainImage());
        orderDetail.setBusinessCode(productResult.getBusinessCode());
        orderDetail.setProductPriceGrade(productResult.getPriceGrade());
        orderDetail.setSoftwareFlag(productResult.getSoftwareFlag());
        orderDetail.setSpecialPrice(productResult.getSpecialPrice());
        orderDetail.setProductUnit(productResult.getUnit());
        orderDetail.setPoItem(productResult.getPoItem());
        orderDetail.setNote(productResult.getNote());
    }

    /**
     * 创建订单及明细
     * @param orderParam 订单参数
     * @param order 订单
     */
    private void createOrderSubject(AppOrderParam orderParam, OrderSubject order) {
        Map<String, List<ProductResult>> resultMap = getSpiltOrderList(orderParam);
        Set<String> keySet = resultMap.keySet();
        Iterator<String> iterator = keySet.iterator();
        while (iterator.hasNext()) {
            String businessCode = iterator.next().toString();
            List<ProductResult> productList = resultMap.get(businessCode);

            // 检查库存计算金额
            checkStockAmount(productList,order);

            // 创建订单主体
            order.setBusinessCode(businessCode);
            order.setOrderCode(OrderUtils.generateOrderCode());
            order.setAuditStatus(Constant.WATTING_TO_AUDITING);
            order.setOrderStatus(Constant.WAITING_TO_PAY);
            order.setPayment(orderParam.getPayment());
            orderMapper.insertSelective(order);

            // 向订单中添加产品明细
            addOrderDetail(productList, order);
        }
    }

    /**
     * 设置经销商其它采购信息
     * @param orderParam 订单参数
     * @param order 订单
     * @param orderParam 订单传入参数
     */
    private void setOtherPurchaseInfo(OrderSubject order, PlatformOrderParam orderParam) {
        String userName = null;
        if (order.getPlatform() == Constant.APP_ORDER) {
            order.setUserType(Constant.ORDINARY);
            userName = userService.getLoginUserName();
            order.setUserId(userService.getLoginUserId());
        } else {
            order.setUserType(orderParam.getUserType());
            AuthUserBean authUserBean = null;
            userName = orderParam.getUserName();
            authUserBean = userService.getAuthUserByUserName(userName);
            if (authUserBean == null || authUserBean.getId() == null) {
                throw new RuntimeException(OrderTip.DEALER_USER_HAVE_NO_LOGIN_PERMISSION);
            }
            order.setUserId(authUserBean.getId());
        }
        // 如果用户未输入收货人姓名
        if (StringUtils.isEmpty(userName)) {
            order.setUserName(userName);
        }
        // 设置区域接单员信息
        UserBean userBean = userService.getUserBeanByName(userName);
        order.setUserNo(userBean.getUserNo());
        order.setUserRegionCode(userBean.getRegionCode());
        if (userBean.getOrderTakeUser() == null) {
            throw new RuntimeException(OrderTip.OREDER_TAKE_USER_IS_NULL);
        }
        order.setOrderTakeUser(userBean.getOrderTakeUser());
    }

    /**
     * 检查库存计算金额
     * @param orderParam 订单参数
     * @param order 订单
     */
    private void checkStockAmount(List<ProductResult> productList, OrderSubject order) {
        String message = null;
        BigDecimal totalAmount = new BigDecimal(0.00);
        BigDecimal specialAmount = new BigDecimal(0.00);
        for (ProductResult productResult : productList) {
            Integer productId = productResult.getId();
            Integer num = productResult.getPurchaseNum();
            message = cartService.checkProductStock(productId, num);
            if (message != null) {
                throw new RuntimeException(message);
            }
            if (productResult.getId() == null) {
                throw new RuntimeException(OrderTip.PRODUCT_NOT_EXIST);
            } else {
                BigDecimal salePrice = productResult.getSalePrice();
                totalAmount = cartService.calculateAmount(totalAmount, salePrice, num);
                if (productResult.getSpecialPrice()!=null){
                    specialAmount = specialAmount.add(productResult.getSpecialPrice());
                }
                totalAmount = totalAmount.add(specialAmount);
            }
        }
        // 设置订单金额
        order.setAmount(totalAmount);
        order.setSpecialAmount(specialAmount);
    }

    /**
     * 订单金额修改权限检查
     * @param param
     * @return
     */
    public int checkPermission(OrderSubject param){
        String loginUser = userService.getLoginUserName();
        if (!loginUser.equals(param.getOrderTakeUser())) {
            return -1;
        }
        return 1;
    }
    /**
     * 修改订单金额
     * @param param
     * @return
     */
    public int updateAmount(OrderSubject param){
        BigDecimal beforeModification = selectOrder(param.getId()).getAmount();
        int num = orderMapper.updateByPrimaryKeySelective(param);
        addUpdateAmountLog(param.getId(),beforeModification);
        return num;
    }

    /**
     * 增加修改金额日志
     * @param id
     */
    public void addUpdateAmountLog(Integer id, BigDecimal beforeModification){
        OrderSubject orderSubject=orderMapper.selectByPrimaryKey(id);
        OrderLog orderLog = new OrderLog();
        orderLog.setOrderCode(orderSubject.getOrderCode());
        orderLog.setUserName(orderSubject.getUserName());
        orderLog.setDescription(orderSubject.getOrderTakeUser()+OrderTip.ORDER_UPDATE_CHANGE+orderSubject.getOrderCode()+OrderTip.UPDATE_BEFORE_AMOUNT+beforeModification+OrderTip.UPDATE_BACK_AMOUNT+orderSubject.getAmount());
        orderLog.setOrderId(id);
        orderLog.setUserId(orderSubject.getUserId());
        orderLog.setType(Constant.LOG_TYPE_UPDATE);
        orderLogService.addOrderLog(orderLog);
    }

    /**
     * 订单状态校验
     * @param param
     * @return
     */
    public Map<String,String> checkOrderStatus(OrderStatusParam param){
        Map<String,String > messMap = new HashedMap();
        OrderSubject beans =new OrderSubject();
        OrderSubjectExample orderSubjectExample =new OrderSubjectExample();
        orderSubjectExample.createCriteria().andSapCodeEqualTo(param.getSapCode()).andDelFlagEqualTo(String.valueOf(0));
        List<OrderSubject> orderSubjecs=orderMapper.selectByExample(orderSubjectExample);
        if(orderSubjecs.size()>0){
            beans=orderSubjecs.get(0);
        }
        if(OrderTip.STRING_CHARACTER_NULL.equals(param.getSapCode()) || OrderTip.STRING_CHARACTER_NULL.equals(param.getCustomerCode())){
            messMap.put(OrderTip.STRING_MESSAGE_ALERT,OrderTip.ERROR_NOT_READ);
        }else if(! beans.getUserNo().equals(param.getCustomerCode())){
            messMap.put(OrderTip.STRING_MESSAGE_ALERT,OrderTip.ERROR_YOU_ORDER);
        }
        return messMap;
    }
    /**
     * 查询订单状态跟踪
     * @param param
     * @return
     */
    public View searchOrderStatus(OrderStatusParam param){
        View view = new View(20000, "获取列表成功");
        Map<String,String> resMap= checkOrderStatus(param);
        view.setData(resMap);
        if(resMap.size()==0){
            view= restTemplate.postForEntity("http://dean-saprfc/saprfc/v1/saprfc/order/status/", param.getSapCode(),
                    View.class).getBody();
            view.setCode(20000);
            view.setMessage("获取列表成功");
        }
        return view;
    }



    /**
     * 设置收货人信息
     * @param orderParam 订单参数
     * @param order 订单
     */
    private void setConsigneeInfo(AppOrderParam orderParam, OrderSubject order) {
        ConsigneeBean consignee = orderParam.getConsignee();
        order.setUserName(consignee.getUserName());
        order.setUserAddress(consignee.getUserAddress());
        order.setUserTelphone(consignee.getUserTelphone());
    }

    /**
     * 按照事业部代码对购物车列表进行分组
     * @param orderParam
     * @return Map<String, List<ProductResult>>
     */
    private Map<String, List<ProductResult>> getSpiltOrderList(AppOrderParam orderParam){
        Integer userId = userService.getLoginUserId();
        Map<String, List<ProductResult>> resultMap = new HashMap<String, List<ProductResult>>();
        List<CartParam> cartList = orderParam.getCartList();
        List<ProductResult> productList = new ArrayList<ProductResult>();
        for (CartParam cartParam : cartList) {
            Integer cartId = cartParam.getId();
            Integer productId = cartParam.getProductId();
            if (cartId != 0) {
                Cart cart = cartService.selectCart(cartId);
                if (cart == null) {
                    throw new RuntimeException(OrderTip.NOT_FOUND_CART);
                }
                if (!cart.getUserId().equals(userId) || !cart.getProductId().equals(productId)) {
                    throw new RuntimeException(OrderTip.NOT_YOUR_CART);
                }
                // 删除购物车
                cart.setDelFlag(String.valueOf("1"));
                cartService.updateCart(cart);
            }
            ProductResult productResult = produtService.getProductBeanById(productId);
            productResult.setPurchaseNum(cartParam.getNum());
            productResult.setNote(cartParam.getNote());
            productList.add(productResult);
        }
        for (ProductResult productResult : productList) {
            String businessCode = productResult.getBusinessCode();
            if (resultMap.containsKey(businessCode)) {
                resultMap.get(businessCode).add(productResult);
            } else {
                List<ProductResult> tmpProductList = new ArrayList<ProductResult>();
                tmpProductList.add(productResult);
                resultMap.put(businessCode, tmpProductList);
            }

        }
        return resultMap;
    }

    /**
     * 订单搜索列表总数
     * @param orderSubjectSearchParam
     * @return
     */
    public Long searchListCount(OrderSubjectSearchParam orderSubjectSearchParam) {
        return orderSubjectExtendsMapper.countByExample(orderSubjectSearchParam);
    }

    /**
     * 订单搜索
     * @param offset
     * @param limit
     * @param orderSubjectSearchParam
     * @return
     */
    public  List<OrderSubjectSearchResult> searchList(int offset, int limit, OrderSubjectSearchParam orderSubjectSearchParam){
        List<OrderSubjectSearchResult> orderSubjects=new ArrayList<OrderSubjectSearchResult>();
        RowBounds rowBounds = new RowBounds(offset, limit);
        List<OrderSubject>  list=orderSubjectExtendsMapper.selectByExampleWithRowbounds(orderSubjectSearchParam,rowBounds);
        for(OrderSubject orderSubjectList :list){

            OrderSubjectSearchResult bean= OrderSubjectSearchResult.coverToBean(orderSubjectList);
            if(orderSubjectList.getCreateDate() !=null){
                bean.setCreateDate(DateProcessUtils.formatTimestampToDate(orderSubjectList.getCreateDate()));
            }
            orderSubjects.add(bean);
        }
        return orderSubjects;
    }

    /**
     * 查询订单详情
     * @param id
     * @return
     */
    public OrderSubjectResult searchOrderdetail(Integer id){
        List<OrderSubjectDetailResult> newList = new ArrayList<OrderSubjectDetailResult>();
        OrderSubjectResult bean = new OrderSubjectResult();
        OrderSubject orderSubject= orderMapper.selectByPrimaryKey(id);
        if (orderSubject == null) {
            return bean;
        }
        bean=OrderSubjectResult.coverToBean(orderSubject);
        bean.setCreateDate(DateProcessUtils.formatTimestampToDate(orderSubject.getCreateDate()));
        bean.setRegion(queryRegionName(orderSubject.getUserRegionCode()));
        List<OrderDetail> orderDetailList = orderDetailService.getOrderDetailList(bean.getOrderCode());
        for(OrderDetail orderDetail : orderDetailList){
            OrderSubjectDetailResult orderDetailBean = OrderSubjectDetailResult.coverToBean(orderDetail);
            List<OrderDetailResult> subOrderDetailResultList = new ArrayList<OrderDetailResult>();
            List<OrderDetail> subOrderDetailList = orderDetailService.getOrderDetailListByUpId(orderDetail.getId());
            for (OrderDetail subOrderDetail : subOrderDetailList) {
                OrderDetailResult subOrderDetailBean = OrderDetailResult.coverToBean(subOrderDetail);
                subOrderDetailResultList.add(subOrderDetailBean);
            }
            orderDetailBean.setChildList(subOrderDetailResultList);;
            newList.add(orderDetailBean);
        }
        bean.setOrderSubjectDetailResultList(newList);

        return bean;

    }

    /**
     * 根据区域编码查询区域名称
     * @param regioCode
     * @return
     */
    public String queryRegionName(String regioCode){

        @SuppressWarnings("rawtypes")
        View result= restTemplate.postForEntity("http://dean-platform/platform/v1/admin/region/name/", regioCode,
                View.class).getBody();

        return (String) result.getData();
    }

    /**
     * 平台代下单
     * @param {@link PlatformOrderParam}
     */
    @Transactional(propagation = Propagation.REQUIRED)
    public int createPlatformOrder(PlatformOrderParam orderParam) {
        OrderSubject order = new OrderSubject();
        order.setPlatform(Constant.PLATFORM_ORDER);
        // 设置收货人信息
        setConsigneeInfo(orderParam,order);
        // 设置经销商其它采购信息
        setOtherPurchaseInfo(order,orderParam);
        // 创建订单及明细
        createOrderSubject(orderParam,order);
        // 修改库存和销量
        updateStockSaleNum(orderParam,order);
        // 增加订单日志
        addOrderLog(order,Constant.LOG_TYPE_ADD);
        return order.getId();
    }

    /**
     * 修改库存和销量
     * @param orderParam 订单参数
     * @param order 订单
     */
    private void updateStockSaleNum(PlatformOrderParam orderParam, OrderSubject order) {
        List<ProductOrderParam> productParamList = orderParam.getProductList();
        for (ProductOrderParam productParam : productParamList) {
            int update = produtService.updateStockSaleNum(productParam);
            if (update == 0) {
                throw new RuntimeException(OrderTip.UPDATE_STOCK_FAIL);
            }
        }
    }

    /**
     * 设置经销商其它采购信息
     * @param orderParam 订单参数
     * @param order 订单
     */
    private void createOrderSubject(PlatformOrderParam orderParam, OrderSubject order) {
        Map<String, List<ProductResult>> resultMap = getSpiltOrderList(orderParam);
        Set<String> keySet = resultMap.keySet();
        Iterator<String> iterator = keySet.iterator();
        while (iterator.hasNext()) {
            String businessCode = iterator.next().toString();
            List<ProductResult> productList = resultMap.get(businessCode);

            // 检查库存计算金额
            checkStockAmount(productList,order);

            // 创建订单主体
            order.setBusinessCode(businessCode);
            order.setOrderCode(OrderUtils.generateOrderCode());
            order.setAuditStatus(Constant.WATTING_TO_AUDITING);
            order.setOrderStatus(Constant.WAITING_TO_PAY);
            order.setPayment(Constant.OFFLINE);
            order.setNote(orderParam.getNote());
            order.setContract(orderParam.getContract());
            order.setSaleGuide(orderParam.getSaleGuide());
            order.setDeliveryUser(orderParam.getDeliveryUser());
            orderMapper.insertSelective(order);

            // 向订单中添加产品明细
            addOrderDetail(productList, order);
        }
    }

    /**
     * 按照事业部代码对提交订单进行拆单
     * @param orderParam
     * @return Map<String, List<ProductResult>>
     */
    private Map<String, List<ProductResult>> getSpiltOrderList(PlatformOrderParam orderParam) {
        Map<String, List<ProductResult>> resultMap = new HashMap<String, List<ProductResult>>();
        List<ProductOrderParam> productParamList =orderParam.getProductList();
        List<ProductResult> productList = new ArrayList<ProductResult>();
        for (ProductOrderParam productParam : productParamList) {
            Integer productId = productParam.getProductId();;
            ProductResult productResult = produtService.getProductBeanById(productId);
            if (productResult == null || productResult.getId() == null) {
                throw new RuntimeException(OrderTip.PRODUCT_NOT_EXIST);
            }
            // 将前台提交的参数装入产品Bean中
            productResult.setSpecialPrice(productParam.getSpecialPrice());
            productResult.setPurchaseNum(productParam.getPurchaseNum());
            productResult.setPoItem(productParam.getPoItem());
            productResult.setNote(productParam.getNote());
            productList.add(productResult);
        }
        for (ProductResult productResult : productList) {
            String businessCode = productResult.getBusinessCode();
            if (resultMap.containsKey(businessCode)) {
                resultMap.get(businessCode).add(productResult);
            } else {
                List<ProductResult> tmpProductList = new ArrayList<ProductResult>();
                tmpProductList.add(productResult);
                resultMap.put(businessCode, tmpProductList);
            }

        }
        return resultMap;
    }

    /**
     * 设置收货人信息
     * @param orderParam 订单参数
     * @param order 订单
     */
    private void setConsigneeInfo(PlatformOrderParam orderParam, OrderSubject order) {
        order.setUserName(orderParam.getUserName());
        order.setUserAddress(orderParam.getAddress());
        order.setUserTelphone(orderParam.getMoible());
    }

    /**
     * 获取APP订单详情(包含订单产品清单详情)
     * @param orderSubject {@link OrderSubject}
     * @return {@link AppOrderResult}
     */
    public AppOrderResult getAppOrderResult(OrderSubject orderSubject) {
        AppOrderResult orderResult = AppOrderResult.covertToBean(orderSubject);
        AuthUserBean authUserBean = userService.getAuthUserByUserName(orderSubject.getOrderTakeUser());
        if (authUserBean != null) {
            orderResult.setContactNumber(authUserBean.getMobile());
        }
        List<AppOrderResult.OrderDetailResult> detailResultList = getOrderDetailList(orderResult.getId(), orderResult);
        orderResult.setOrderDetailList(detailResultList);
        return orderResult;
    }

    /**
     * 查询订单下的产品列表
     * @param orderId 订单ID
     * @return List<{@link AppOrderResult.OrderDetailResult}>
     */
    private List<AppOrderResult.OrderDetailResult> getOrderDetailList(Integer orderId, AppOrderResult orderResult) {
        Integer total = 0;
        List<AppOrderResult.OrderDetailResult> detailResultList = new ArrayList<AppOrderResult.OrderDetailResult>();
        List<OrderDetail> orderDetailList = orderDetailService.getOrderDetailList(orderId);
        for (OrderDetail orderDetail : orderDetailList) {
            total += orderDetail.getPurchaseQuantity();
            AppOrderResult.OrderDetailResult detailResult = AppOrderResult.OrderDetailResult.covertToBean(orderDetail);
            detailResult.setProductImage(aliyunOssTool.getImgUrl(orderDetail.getProductImage()));
            detailResultList.add(detailResult);
        }
        orderResult.setTotal(total);
        return detailResultList;
    }

    /**
     * 确认收货并将将采购产品写入经销商品店铺产品
     * @param order 订单
     */
    @Transactional(propagation = Propagation.REQUIRED)
    public void confirmReceive(OrderSubject order) {
        // 修改订单状态
        updateOrder(order);
       // 将采购产品写入经销商品店铺产品
       String userName = userService.getLoginUserName();
       UserBean userBean  = userService.getUserBeanByName(userName);
       Integer storeId = userBean.getStoreId();
       List<OrderDetail> orderDetailList = orderDetailService.getOrderDetailList(order.getId());
       List<OrderDetailBean> orderDetailBeanList = OrderDetailBean.covertToBeanList(orderDetailList);
       storeService.saveStoreProduct(storeId,orderDetailBeanList);
    }

    /**
     * 取消订单并还原库存和销量
     * @param order 订单
     */
    @Transactional(propagation = Propagation.REQUIRED)
    public void cancelOrder(OrderSubject order) {
        // 修改订单状态
        updateOrder(order);
        // 还原库存和销量
        List<OrderDetail> orderDetailList = orderDetailService.getOrderDetailList(order.getId());
        for (OrderDetail orderDetail : orderDetailList) {
            ProductOrderParam prodcutParam = new ProductOrderParam();
            prodcutParam.setProductId(orderDetail.getProductId());
            prodcutParam.setPurchaseNum(-orderDetail.getPurchaseQuantity());
            produtService.updateStockSaleNum(prodcutParam);
        }
        // 增加订单操作日志
        addOrderLog(order,Constant.LOG_TYPE_UPDATE);
    }

    /**
     * 重新购买并修改库存和销量
     * @param order 订单
     */
    @Transactional(propagation = Propagation.REQUIRED)
    public void reBuy(OrderSubject order) {
        // 修改订单状态
        updateOrder(order);
        // 还原库存和销量
        List<OrderDetail> orderDetailList = orderDetailService.getOrderDetailList(order.getId());
        for (OrderDetail orderDetail : orderDetailList) {
            ProductOrderParam prodcutParam = new ProductOrderParam();
            prodcutParam.setProductId(orderDetail.getProductId());
            prodcutParam.setPurchaseNum(orderDetail.getPurchaseQuantity());
            produtService.updateStockSaleNum(prodcutParam);
        }
    }

    /**
     * 查询需要传输的订单数据
     * @param orderCode
     * @return orderSubjectResults
     */
    public OrderSubjectResult getOrderData(String orderCode){
        OrderSubjectResult orderSubjectResults = new OrderSubjectResult();
        OrderSubjectExample example =new OrderSubjectExample();
        example.createCriteria().andOrderCodeEqualTo(orderCode);
        List<OrderSubject> list = orderMapper.selectByExample(example);
        for(OrderSubject orderSubject : list){
            orderSubjectResults= OrderSubjectResult.coverToBean(orderSubject);
            orderSubjectResults.setCreateDate(DateProcessUtils.formatTimestampToDate(orderSubject.getCreateDate()));
        }
        List<OrderSubjectDetailResult> details = orderSubjectExtendsMapper.selectByExample(orderSubjectResults.getId());

        orderSubjectResults.setOrderSubjectDetailResultList(details);
        return orderSubjectResults;
    }


    /**
     * 订单传输校验
     * @param orderTransmitParam
     * @return
     */
    public Map<String,String> checkOrderData(OrderTransmitParam orderTransmitParam,OrderSubjectResult result){
        Map<String,String> messageMap = new HashedMap();
        String checkDivisionCode="";
        for(OrderSubjectDetailResult bean : result.getOrderSubjectDetailResultList()){
            if(! result.getBusinessCode().equals(bean.getBusinessCode())){
                //事业部代码检查
                checkDivisionCode=OrderTip.ERROR_BUSINESS_NOT;
            }
        }
        if(OrderTip.STRING_CHARACTER_NULL.equals(orderTransmitParam.getOrderCode())){
            //输入订单号为空检查
            messageMap.put(OrderTip.STRING_MESSAGE_ALERT,OrderTip.ERROR_PLEASE_ORDER);
        }else if(OrderTip.STRING_CHARACTER_NULL.equals(result.getBusinessCode()) || ! OrderTip.STRING_CHARACTER_NULL.equals(checkDivisionCode)){
            //事业部代码检查
            messageMap.put(OrderTip.STRING_MESSAGE_ALERT,OrderTip.ERROR_BUSINESS_MULTI);
        }else if(OrderTip.STRING_CHARACTER_NULL.equals(result.getId())){
            //订单号不存在
            messageMap.put(OrderTip.STRING_MESSAGE_ALERT,OrderTip.ERROR_ORDER_NOT);
        }else if("1".equals(result.getDelFlag())){
            //订单删除检查
            messageMap.put(OrderTip.STRING_MESSAGE_ALERT,OrderTip.ERROR_ORDER_DELET);
        }else if(result.getSapCode()!=null || result.getAuditStatus()==2 ){
            //是否传入SAP检查
            messageMap.put(OrderTip.STRING_MESSAGE_ALERT,OrderTip.ERROR_ORDER_INTRODUCTION);
        }else if(0 == result.getOrderSubjectDetailResultList().size()){
            //是否有明细数据检查
            messageMap.put(OrderTip.STRING_MESSAGE_ALERT,OrderTip.ERROR_ORDER_DETAIL);
        }else if(OrderTip.STRING_CHARACTER_NULL.equals(result.getSapAccount())){
            //sap账号为空检查
            messageMap.put(OrderTip.STRING_MESSAGE_ALERT,OrderTip.ERROR_SAP_ID);
        }

        return messageMap;
    }

    /**
     * 订单处理
     * @param param
     * @return
     */
    public Map<String, String> orderToSap(OrderTransmitParam param){
        Map<String,String> returnMessMap = new HashedMap();
        OrderSubjectResult result = getOrderData(param.getOrderCode());
        //获取接单员的sap账号
        result.setSapAccount(querySapAccount());
        //校验
        returnMessMap = checkOrderData(param,result);
        if(returnMessMap.size()==0){
            //订单传输
            returnMessMap = synOrder(result);
            if(returnMessMap.get(OrderTip.SAP_OREDER_CODE) != null){
                //修改订单状态 和 sap返回的订单号
                OrderSubject order =new OrderSubject();
                order.setId(result.getId());
                order.setAuditStatus(Constant.SYNCHRONIZED);
                order.setSapCode(returnMessMap.get(OrderTip.SAP_OREDER_CODE));
                updateOrder(order);
            }
        }
        return returnMessMap;
    }

    /**
     * 订单传输
     * @param orderResult
     * @return
     */
    public Map<String, String> synOrder(OrderSubjectResult orderResult){
        Map<String, String>  resMap = new HashedMap();
        View view = restTemplate.postForEntity("http://dean-saprfc/saprfc/v1/saprfc/order/transmit/", orderResult,
                View.class).getBody();
        if(view.getCode()==20000 && view.getData() != null){
            resMap= (Map<String, String>) view.getData();
        }

        return resMap;
    }

    /**
     * 查询接单员对应的sap账号
     * @return
     */
    public String querySapAccount(){
        Long id = tokenPrincipalProvider.getTokenPrincipal().getUserId();
        String sapAccount="";
        View<String> result =  restTemplate.postForEntity("http://dean-auth/auth/v1/inner/auth/user/search/sap/account/"+id, null,
                View.class).getBody();
         if(result.getCode() == 20000 && result.getData() != null){
             sapAccount=result.getData();
         }
         return sapAccount;
    }

    /**
     * 修改app订单发货状态
     * @param maps
     * @return
     */
    public int updateAppOrderStauts(Map<String,String> maps){
        int updateCount=0;
        OrderSubjectExample example = new OrderSubjectExample();
        OrderSubject orderSubject = new OrderSubject();
        OrderSubject order = new OrderSubject();
        OrderSubjectExample orderSubjectExample = new OrderSubjectExample();
         for(String str : maps.keySet()){
                if(StringUtils.isNotBlank(maps.get("ponum")) && StringUtils.isNotBlank(maps.get("status"))){
                    if("3".equals(maps.get("status"))){
                        //更改订单状态
                        example.createCriteria().andOrderCodeEqualTo(maps.get("ponum"));
                        orderSubject.setOrderStatus(Constant.WAITING_TO_RECEIVE);
                        updateCount += orderMapper.updateByExampleSelective(orderSubject,example);
                        //订单状态消息推送
                        orderSubjectExample.createCriteria().andOrderCodeEqualTo(maps.get("ponum")).andDelFlagEqualTo(OrderSubject.DEL_FLAG_NORMAL);
                        order = CollectionUtils.isNotEmpty(orderMapper.selectByExample(orderSubjectExample)) ? orderMapper.selectByExample(orderSubjectExample).get(0) : new OrderSubject();
                        pushService.addAndPushMessage(order);
                    }
                }
         }

        return updateCount;
    }
    
    /**
     * 待发货订单列表
     * @param order
     * @return
     */
    public List<OrderSubject> getWaittingToDeliverOrderList() {
        OrderSubjectExample example = new OrderSubjectExample();
        OrderSubjectExample.Criteria criteria = example.createCriteria();
        criteria.andAuditStatusEqualTo(Constant.SYNCHRONIZED);
        criteria.andOrderStatusEqualTo(Constant.WAITING_TO_PAY);
        criteria.andDelFlagEqualTo(OrderSubject.DEL_FLAG_NORMAL);
        return orderMapper.selectByExample(example);
    }

    /**
     * 修改订单产品金额
     * @param orderProductParam
     */
    @Transactional
    public void updateOrderProductPrice(OrderProductParam orderProductParam) {
        Integer orderId = orderProductParam.getId();
        OrderSubject order = orderMapper.selectByPrimaryKey(orderId);
        // 检查库存计算金额
        List<ProductResult> productList = new ArrayList<ProductResult>();
        List<OrderProductParam.OrderDetailParam> orderDetailList = orderProductParam.getOrderDetailList();
        for (OrderProductParam.OrderDetailParam orderDeailParam : orderDetailList) {
            OrderDetail orderDetail = orderDetailService.selectOrderDetail(orderDeailParam.getId());
            ProductResult productResult = new ProductResult();
            BeanUtils.copy(orderDeailParam, productResult);
            productResult.setId(orderDetail.getProductId());
            productResult.setSalePrice(orderDetail.getProductPrice());
            productResult.setPurchaseNum(orderDeailParam.getPurchaseQuantity());
            productList.add(productResult);
        }
        checkStockAmount(productList,order);
        // 修改订单产品明细
        for (OrderProductParam.OrderDetailParam orderDeailParam : orderDetailList) {
            OrderDetail orderDetail = orderDetailService.selectOrderDetail(orderDeailParam.getId());
            if (orderDetail.getOrderId().equals(orderId)) {
                BeanUtils.copy(orderDeailParam, orderDetail);
                BigDecimal purchaseNum = new BigDecimal(orderDetail.getPurchaseQuantity());
                orderDetail.setAmount(orderDetail.getProductPrice().multiply(purchaseNum));
                orderDetailService.updateOrderDetail(orderDetail);
            } else {
                throw new RuntimeException(OrderTip.ORDER_AND_DETAIL_NOT_MATCH);
            }
        }
        orderMapper.updateByPrimaryKey(order);
    }
}
